package com.relsell.view;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.relsell.admin.Admin;
import com.relsell.admin.DbHelper;
import com.relsell.pointofsales.R;
import com.relsell.utility.AppVars;
import com.relsell.utility.ChangeRoleService;
import com.relsell.utility.UtilitySingleTon;

public class Login extends Activity implements OnClickListener {


	Button ok;
	Button clear;
	EditText et, et2;
	String user, pass;
	TextView tv;
	String result;
	Activity ct = this;
	String userid;
	String error;
	static String logedinuserid;
	/* gcm id*/
	private GoogleCloudMessaging gcm;
	private String regid;
	public static final String SENDER_ID = "662012642984";   // gcm sender id
	public static final String sUserName = "username";
	public static final String sPassword = "password";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().requestFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setContentView(R.layout.login);
		//AppVars.dbFromBackup(this);
		//insertDummyUsersDataInUserTable();
		AppVars.dbBackup(this);
		
		gcm = GoogleCloudMessaging.getInstance(this);
		new GetGCMIDFromGCMServer().execute();
		et = (EditText) findViewById(R.id.etUsername);
		et2 = (EditText) findViewById(R.id.etPass);
		tv = (TextView) findViewById(R.id.textViewError);
		ok = (Button) findViewById(R.id.btnSubmit);
		clear = (Button)findViewById(R.id.btnClear);
		ok.setOnClickListener(this);
		clear.setOnClickListener(this);
	}

	@Override
	public void onClick(View view) {
		if (view == ok) {
			ok.setPressed(true);
			//ok.setVisibility(View.INVISIBLE);
			this.setProgressBarIndeterminateVisibility(true);
			new SendTask().execute();
		} else if (view == clear){
			et.setText("");
			et2.setText("");
			tv.setText("");
			clear.setVisibility(View.GONE);
		}
		
	}

	public class SendTask extends AsyncTask<Void, Void, Boolean> {

		String responseString;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();

		}

		@Override
		protected Boolean doInBackground(Void... params) {
			try {

				HttpClient http = new DefaultHttpClient();
				String server = AppVars.getServer();
				System.out.println("http://"+server+"/gcminteraction/view/start.php?controlVar=1");
				HttpPost post = new HttpPost(
						"http://"+server+"/gcminteraction/view/start.php?controlVar=1");

				user = et.getText().toString();
				pass = et2.getText().toString();
				List<NameValuePair> data = new ArrayList<NameValuePair>();
				data.add(new BasicNameValuePair(sUserName, user));
				data.add(new BasicNameValuePair(sPassword, pass));
				post.setEntity(new UrlEncodedFormEntity(data));
				

				HttpResponse response = http.execute(post);
				responseString = new BasicResponseHandler()
						.handleResponse(response); // Basic handler
				
				if(AppVars.isLogEnabled) {
					Log.v(AppVars.LOG_TAG,"Response String ="+responseString);
				}
				try {
					JSONObject obj = new JSONObject(responseString);

					error = obj.getString("error");
					if (error.equals("true")) {
						result = obj.getString("loggedIn");
						userid = obj.getString("loggedInUserType");
						logedinuserid = obj.getString("loggedInUserId");
						AppVars.sloggedInUserId = obj
								.getString("loggedInUserId");
						AppVars.sloggedInUserType = obj
								.getString("loggedInUserType");
					}

				} catch (JSONException e) {

					e.printStackTrace();
				}

				return true;
			} catch (ClientProtocolException e) {
				e.printStackTrace();

			} catch (IOException e) {
				e.printStackTrace();
			}
			return false;
		}

		@Override
		protected void onPostExecute(Boolean success) {
			
			if(AppVars.isLogEnabled) {
				Log.v(AppVars.LOG_TAG,"Logged User ID "+userid);
			}
			if(AppVars.isLogEnabled) {
				Log.v(AppVars.LOG_TAG,"error "+error);
			}
			if((error == null || error.equals("true")) && userid.equals("1") && result.equals("true"))
			{
			ct.setProgressBarIndeterminateVisibility(false);
			Intent intent=new Intent(Login.this,Manager.class);
			intent.putExtra("username",et.getText().toString());
			startActivity(intent);
			finish();
			}
			else if((error == null || error.equals("true")) && userid.equals("2") && result.equals("true"))
			{
				ct.setProgressBarIndeterminateVisibility(false);
				Intent intent=new Intent(Login.this,NormalUser.class);
				intent.putExtra("username",et.getText().toString());
				startActivity(intent);
				finish();
				
			}
			else if( (error == null || error.equals("true")) && userid.equals("3") && result.equals("true"))
			{
				ct.setProgressBarIndeterminateVisibility(false);
				Intent intent=new Intent(Login.this,Admin.class);
				intent.putExtra("username",et.getText().toString());
				startActivity(intent);
				finish();
			}
			else
			{
				if (error.equals("10001")) { 
					
				    tv.setText(Login.this.getResources().getString(R.string.db_error));
				    clear.setVisibility(View.VISIBLE);
				} else {
		
					tv.setText(Login.this.getResources().getString(R.string.username_password_error));
				}
				et.setText("");
				et2.setText("");
				ct.setProgressBarIndeterminateVisibility(false);
				ok.setVisibility(View.VISIBLE);
			}
		}
	}
	
	public class GetGCMIDFromGCMServer extends AsyncTask<String,Void,String>{

		@Override
		protected String doInBackground(String... params) {
			//TODO: this needs to be integrated
			String msg = "";
			try {
				if (gcm == null) {
					gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
				}
				regid=gcm.register(SENDER_ID);
				if (regid != null && regid != "") {
				    UtilitySingleTon.getInstance().setgCMRegId(regid);
				}
				msg = "Device registered, registration ID=" + regid;
				
				System.out.println(msg);
			} catch (IOException ex) {
				msg = "Error :" + ex.getMessage();
				// If there is an error, don't just keep trying to register.
				// Require the user to click a button again, or perform
				// exponential back-off.
			}
			return msg;
		}
		
	}
	
	public void insertDummyUsersDataInUserTable() {

		DbHelper db=new DbHelper(this);
		db.open();
		db.insertInUserTable("1","anil","1");
		db.insertInUserTable("2","relsell","1");
		db.insertInUserTable("3","admin","3");
		db.insertInUserTable("1","manager","2");
		db.close();
	}

}